#include "stm32f10x.h"                  // Device header
#include "My_SPI.h"
#include "W25Q64_Ins.h"


/*
W25Q64初始化
*/
void W25Q64_Init(void)
{
	MySPI_Init();
}

/*
W25Q64读取ID
*/
void W25Q64_ReadID(uint8_t *MID, uint16_t *DID)
{
	MySPI_Start();
	MySPI_Swap_ByteSend(W25Q64_JEDEC_ID);
	*MID = MySPI_Swap_ByteSend(W25Q64_DUMMY_BYTE);
	*DID = MySPI_Swap_ByteSend(W25Q64_DUMMY_BYTE);
	*DID <<= 8;
	*DID |= MySPI_Swap_ByteSend(W25Q64_DUMMY_BYTE);
	MySPI_Stop();
}

/*
W25Q64写使能
*/
void W25Q64_WriteEnable(void)
{
	MySPI_Start();
	MySPI_Swap_ByteSend(W25Q64_WRITE_ENABLE);
	MySPI_Stop();
}

/*
W25Q64等待忙
*/
void W25Q64_WaitBusy(void)
{
	uint32_t Timeout = 100000;
	MySPI_Start();
	MySPI_Swap_ByteSend(W25Q64_READ_STATUS_REGISTER_1);
	while ((MySPI_Swap_ByteSend(W25Q64_READ_STATUS_REGISTER_1) & 0x01) == 0x01)
	{
		if(Timeout --)
			{
			break;
			}
	}
	MySPI_Stop();
}


/*
W25Q64页编程
*/
void W25Q64_PageProgram(uint32_t Address, uint8_t * DataArray, uint16_t count)
{
	uint16_t i;
	// 计次用uint16_t 因为uint8_t 只能到255, 而一页最多可以写256
	MySPI_Start();
	MySPI_Swap_ByteSend(W25Q64_PAGE_PROGRAM);
	// "高位舍弃"
	MySPI_Swap_ByteSend(Address >> 16);
	MySPI_Swap_ByteSend(Address >> 8);
	MySPI_Swap_ByteSend(Address);
	for (i = 0; i < count; i ++)
	{
		MySPI_Swap_ByteSend(DataArray[i]);
	}
	MySPI_Stop();
	
	W25Q64_WaitBusy();
}


/*
W25Q64扇区擦除
*/
void W25Q64_SectorErase(uint32_t Address)
{
	MySPI_Start();
	MySPI_Swap_ByteSend(W25Q64_SECTOR_ERASE_4KB);
	// "高位舍弃"
	MySPI_Swap_ByteSend(Address >> 16);
	MySPI_Swap_ByteSend(Address >> 8);
	MySPI_Swap_ByteSend(Address);
	MySPI_Stop();
	
	W25Q64_WaitBusy();
}

/*
W25Q64扇区擦除
*/
void W25Q64_ReadData(uint32_t Address, uint8_t *DataArray, uint16_t count)
{
	uint16_t i;
	MySPI_Start();
	MySPI_Swap_ByteSend(W25Q64_READ_DATA);
	// "高位舍弃"
	MySPI_Swap_ByteSend(Address >> 16);
	MySPI_Swap_ByteSend(Address >> 8);
	MySPI_Swap_ByteSend(Address);
	for (i = 0; i < count; i ++)
	{
		DataArray[i] = MySPI_Swap_ByteSend(W25Q64_DUMMY_BYTE);
	}
	MySPI_Stop();
	// 读数据不需要等忙
//	W25Q64_WaitBusy();
}
